/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.reflection.parameter;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 1/6/2017
 */
public class PositionalParameterNameFinder implements ParameterNameFinder {

    public final String prefix;

    /**
     * Default Contstructor with prefix <code>arg</code>.
     */
    public PositionalParameterNameFinder() {
        this(PARAM_DEFAULT_PREFIX);
    }

    /**
     * Constructor that allows to override the prefix.
     *
     * @param prefix
     *            string that is prepended before the position of the parameter.
     */
    public PositionalParameterNameFinder(String prefix) {
        super();
        this.prefix = prefix;
    }

    public String[] findParameterNames(AccessibleObject methodOrConstructor) {
        return findParameterNames(methodOrConstructor, true);
    }

    public String[] findParameterNames(AccessibleObject methodOrCtor,
                                         boolean throwExceptionIfMissing) {
        int count = count(methodOrCtor);
        String[] result = new String[count];
        for (int i = 0; i < result.length; i++) {
            result[i] = prefix + i;
        }
        return result;
    }

    private int count(AccessibleObject methodOrCtor) {
        if (methodOrCtor instanceof Method) {
            Method method = (Method) methodOrCtor;
            return method.getParameterTypes().length;
        }
        Constructor<?> constructor = (Constructor<?>) methodOrCtor;
        return constructor.getParameterTypes().length;
    }

}
